<?php
require_once __DIR__.'/ErrorCode.php';
class Article
{
    /**
     * [private 数据库资源句柄]
     * @var [PDO]
     */
    private $_db;
    
    /**
     * [__construct 实例化传入数据库资源句柄]
     * @param [type] $_db [description]
     */
    public function __construct($_db)
    {
        $this->_db=$_db;
    }
    
    /**
     * [create 创建文章]
     * @param  [type] $title   [description]
     * @param  [type] $content [description]
     * @param  [type] $userId  [description]
     * @return [type]          [description]
     */
    public function create($title,$content,$userId)
    {
        if(empty($title)){
            throw new Exception('文章标题不能为空',ErrorCode::ARTICLE_TITLE_CANNOT_EMPTY);
        }
        if(empty($content)){
            throw new Exception('文章内容不能为空',ErrorCode::ARTICLE_CONTENT_CANNOT_EMPTY);
        }
        $sql='INSERT INTO `article`(`title`,`content`,`user_id`,`created_at`) VALUES(:title,:content,:userId,:createdAt)';
        $createdAt=date('Y-m-d H:i:s',time());
        $stmt=$this->_db->prepare($sql);
        $stmt->bindParam(':title',$title);
        $stmt->bindParam(':content',$content);
        $stmt->bindParam(':userId',$userId);
        $stmt->bindParam(':createdAt',$createdAt);
        
        if(!$stmt->execute()){
            throw new Exception('发表文章失败',ErrorCode::ARTICLE_CREATE_FAIL);
        }
        
        return [
            'articleId'=>$this->_db->lastInsertId(),
            'title'=>$title,
            'content'=>$content,
            'userId'=>$userId,
            'createdAt'=>$createdAt
        ];
    }
    
    /**
     * [view 查看一篇文章]
     * @param  [type] $articleId [description]
     * @return [type]            [description]
     */
    public function view($articleId)
    {
        if(empty($articleId)){
            throw new Exception('文章id不能为空',ErrorCode::ARTICLE_ID_CANNOT_EMPTY);
        }
        
        $sql='SELECT * FROM `article` WHERE `article_id`=:id';
        $stmt=$this->_db->prepare($sql);
        // var_dump($stmt);exit;
        $stmt->bindParam(':id',$articleId);
        $stmt->execute();
        $article=$stmt->fetch(PDO::FETCH_ASSOC);
        
        if(empty($article)){
            throw new Exception('文章不存在',ErrorCode::ARTICLE_NOT_FOUND);
        }
        
        return $article;
    }
    
    /**
     * [edit 编辑文章]
     * @param  [type] $articleId [description]
     * @param  [type] $title     [description]
     * @param  [type] $content   [description]
     * @param  [type] $userId    [description]
     * @return [type]            [description]
     */
    public function edit($articleId,$title,$content,$userId)
    {
        $article=$this->view($articleId);
        // var_dump($article);exit;
        if($article['user_id'] !== $userId){
            throw new Exception('您无权编辑该文章',ErrorCode::PERMISSION_DENIED);
        }
        
        $title=empty($title)? $article['title']:$title;
        $content=empty($content)? $article['content']:$content;
        if($title === $article['title'] && $content ===$article['content']){
            return $article;
        }
        
        $sql='UPDATE `article` SET `title`=:title, `content`=:content WHERE `article_id`=:id';
        $stmt=$this->_db->prepare($sql);
        $stmt->bindParam(':title',$title);
        $stmt->bindParam(':content',$content);
        $stmt->bindParam(':id',$articleId);
        
        if(!$stmt->execute()){
            throw new Exception('文章编辑失败',ErrorCode::ARTICLE_EDIT_FAIL);
        }
        
        return [
            'article_id'=>$articleId,
            'title'=>$title,
            'content'=>$content,
            'created_at'=>$article['created_at']
        ];
    }
    
    /**
     * [delete 删除文章]
     * @param  [type] $articleId [description]
     * @param  [type] $userId    [description]
     * @return [type]            [description]
     */
    public function delete($articleId,$userId)
    {
        $article=$this->view($articleId);
        if($article['user_id'] !== $userId){
            throw new Exception('您无权限操作',ErrorCode::PREMISSION_DENIED);
        }
        
        $sql='DELETE FROM `article` WHERE `article_id`=:articleId AND `user_id`=:userId';
        $stmt=$this->_db->prepare($sql);
        $stmt->bindParam(':articleId',$articleId);
        $stmt->bindParam(':userId',$userId);
        if(false === $stmt->execute()){
            throw new Exception('删除失败',ErrorCode::ARTICLE_DELETE_FAIL);
        }
        return true;
    }
    
    /**
     * [getList 读取文章数据]
     * @param  [type]  $userId [description]
     * @param  integer $page   [description]
     * @param  integer $size   [description]
     * @return [type]          [description]
     */
    public function getList($userId,$page=1,$size=10)
    {
        if($size>100){
            throw new Exception('分页大小最大为100',ErrorCode::PAGE_SIZE_TO_BIG);
        }
        
        $sql='SELECT * FROM `article` WHERE `user_id`=:userId LIMIT :limit,:offset';
        $limit=($page-1)*$size;
        $limit=$limit<0? 0:$limit;
        $stmt=$this->_db->prepare($sql);
        $stmt->bindParam(':userId',$userId);
        $stmt->bindParam(':limit',$limit);
        $stmt->bindParam(':offset',$size);
        $stmt->execute();
        $data=$stmt->fetchAll(PDO::FETCH_ASSOC);
        return $data;
    }
}
